/*
 * @Author: 黑白灰01 3193273703@qq.com
 * @Date: 2025-09-10 10:37:53
 * @LastEditors: 黑白灰01 3193273703@qq.com
 * @LastEditTime: 2025-09-10 17:18:01
 * @FilePath: /auth/src/user/user.service.ts
 * @Description: 用户业务逻辑
 *
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { Role } from './enum';
@Injectable()
export class UserService {
  // 将配置参数作为类属性而不是构造函数参数
  private readonly saltRounds = 10;
  private readonly jwtSecret = 'S407server';
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}

  async create(createUserDto: CreateUserDto) {
    let user = new User();
    user = Object.assign(user, createUserDto);
    user.password = await this.encryptPassword(user.password);
    user.Role = Role.USER;
    await this.usersRepository.save(user);
    return user.id;
  }

  async login(createUserDto: CreateUserDto) {
    const user = await this.usersRepository.findOne({
      where: {
        username: createUserDto.username,
      },
    });
    if (!user) {
      throw new UnauthorizedException("用户名或密码错误");
    }
    if (!(await this.validatePassword(createUserDto.password, user.password))) {
      throw new UnauthorizedException("用户名或密码错误");
    }
    const payload = { sub: user?.id, username: user?.username };
    // 使用实例变量jwtSecret确保密钥一致性
    return { token: this.jwtService.sign(payload, { 
      secret: this.jwtSecret
    }) };
  }

  findAll() {
    return `This action returns all user`;
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
  

  /**
   * @description: 密码加密
   * @param {string} password
   * @return {*}
   */
  async encryptPassword(password: string) {
    const salt = await bcrypt.genSalt(this.saltRounds);
    // 用盐加密密码
    const hashedPassword = await bcrypt.hash(password, salt);

    return hashedPassword;
  }
  /**
   * @description: 密码验证
   * @param {string} password
   * @param {string} hashedPassword
   * @return {*}
   */
  async validatePassword(password: string, hashedPassword: string) {
    return await bcrypt.compare(password, hashedPassword);
  }
}